package com.cyb.beta.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author chenyongbo
 * @date 2016/9/8.
 */
public abstract class OneThreadJob {
    private static final Logger logger = LoggerFactory.getLogger(OneThreadJob.class);
    private final AtomicBoolean running = new AtomicBoolean(false);

    public OneThreadJob() {
    }

    public boolean tryCAS() {
        return this.running.compareAndSet(false, true);
    }

    public final void run() {
        try {
            this.doRun();
        } catch (Throwable e) {
            logger.error("OneThreadJob运行错误:" + this, e);
        } finally {
            this.running.set(false);
        }
    }

    protected abstract void doRun();
}
